package cn.yanhu.kuwanapp.widgets;

import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

import androidx.annotation.Nullable;

import cn.yanhu.kuwanapp.R;


/**
 * @author: witness
 * created: 2020-10-13
 * desc:
 */
public class LoopProgressBar extends View {

    private final int DEGREE_PROGRESS_DISTANCE = dipToPx(5);
    private float startAngle = 270;
    private float sweepAngle = 360;
    private float currentAngle = 360;
    // 内环半径
    private float innerRadius;
    // 进度条宽度
    private float progressWidth;
    // 转一圈的时间
    private Integer duration;
    private RectF rectF;
    private float centerX; //圆心X坐标
    private float centerY; //圆心Y坐标
    private Paint progressBg;
    private Paint progressPaint;
    private int bgColor;
    private int progressColor;
    private ValueAnimator progressAnimator;

    private PaintFlagsDrawFilter mDrawFilter;

    public LoopProgressBar(Context context) {
        super(context, null);
        initView();
    }

    public LoopProgressBar(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs, 0);
        initCofig(context, attrs);
        initView();
    }

    public LoopProgressBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initCofig(context, attrs);
        initView();
    }

    /**
     * 初始化布局配置
     *
     * @param context
     * @param attrs
     */
    private void initCofig(Context context, AttributeSet attrs) {
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.LoopProgressBar);


        innerRadius = a.getDimension(R.styleable.LoopProgressBar_inner_loop_radius, dipToPx(28));
        progressWidth = a.getDimension(R.styleable.LoopProgressBar_progress_width, dipToPx(2));
        duration = a.getInteger(R.styleable.LoopProgressBar_duration, 1000);
        bgColor = a.getColor(R.styleable.LoopProgressBar_background_color, Color.WHITE);
        progressColor = a.getColor(R.styleable.LoopProgressBar_progress_color, Color.GREEN);
        a.recycle();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = (int) (2 * innerRadius +  2 * progressWidth + 2 * DEGREE_PROGRESS_DISTANCE);
        int height = (int) (2 * innerRadius + 2 * progressWidth + 2 * DEGREE_PROGRESS_DISTANCE);
        setMeasuredDimension(width, height);
    }

    private void initView() {
        //弧形的矩阵区域
        rectF = new RectF();
        rectF.top = DEGREE_PROGRESS_DISTANCE + progressWidth / 2;
        rectF.left = DEGREE_PROGRESS_DISTANCE + progressWidth / 2;
        rectF.right = DEGREE_PROGRESS_DISTANCE + progressWidth + innerRadius * 2 + progressWidth / 2;
        rectF.bottom = DEGREE_PROGRESS_DISTANCE + progressWidth + innerRadius * 2 + progressWidth / 2;

        //圆心
        centerX = progressWidth + innerRadius + DEGREE_PROGRESS_DISTANCE;
        centerY = progressWidth + innerRadius + DEGREE_PROGRESS_DISTANCE;


        //整个弧形
        progressBg = new Paint();
        progressBg.setAntiAlias(true);
        progressBg.setStyle(Paint.Style.STROKE);
        progressBg.setStrokeWidth(progressWidth);
        progressBg.setColor(bgColor);
        progressBg.setStrokeCap(Paint.Cap.ROUND);

        //当前进度的弧形
        progressPaint = new Paint();
        progressPaint.setAntiAlias(true);
        progressPaint.setStyle(Paint.Style.STROKE);
        progressPaint.setStrokeCap(Paint.Cap.ROUND);
        progressPaint.setStrokeWidth(progressWidth);
        progressPaint.setColor(progressColor);
//        LinearGradient lg = new LinearGradient(centerX - diameter / 2, centerY, centerX + diameter / 2, centerY - diameter / 2, Color.parseColor("#198BFF"), Color.parseColor("#36BFFF"), Shader.TileMode.MIRROR);
//        progressPaint.setShader(lg);

        mDrawFilter = new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.setDrawFilter(mDrawFilter);
        //整个弧
        canvas.drawArc(rectF, startAngle, sweepAngle, false, progressBg);

        //当前进度
        canvas.drawArc(rectF, startAngle, currentAngle, false, progressPaint);

        invalidate();
    }

    /**
     * 设置当前转动角度
     *
     * @param angle
     */
    public void setCurrentAngle(float angle) {
        if (angle > sweepAngle) {
            currentAngle = sweepAngle;
        }
        if (angle < 0) {
            currentAngle = 0;
        }
        this.currentAngle = angle;
        setAnimation(0, angle, duration);
    }

    /**
     * 为进度设置动画
     *
     * @param start
     * @param current
     */
    @SuppressLint("WrongConstant")
    private void setAnimation(float start, float current, int length) {
        progressAnimator = ValueAnimator.ofFloat(start, current);
        progressAnimator.setDuration(length);
        progressAnimator.setRepeatMode(ValueAnimator.INFINITE);
        progressAnimator.setRepeatCount(ValueAnimator.INFINITE);
        progressAnimator.setTarget(currentAngle);
        progressAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                currentAngle = (Float) animation.getAnimatedValue();
//                curValues = currentAngle / k;
            }
        });
        progressAnimator.start();
    }

    public void pauseProgress(){
        if (progressAnimator != null && progressAnimator.isRunning())
            progressAnimator.pause();
    }

    public void startProgress(){
        Log.d("startProgress", progressAnimator.isRunning() + "---" + progressAnimator.isRunning() + "---" + progressAnimator.isPaused());
        if (progressAnimator != null && progressAnimator.isPaused())
            progressAnimator.resume();
    }

    /**
     * dip 转换成px
     *
     * @param dip
     * @return
     */
    private int dipToPx(float dip) {
        float density = getContext().getResources().getDisplayMetrics().density;
        return (int) (dip * density + 0.5f * (dip >= 0 ? 1 : -1));
    }
}
